<template>
  <van-cell-group>
    <van-swipe class="swipe" :autoplay="3000" :style="maxHeight">
      <van-swipe-item v-for="(item,index) in goods_detail.goods_images" :key="index">
        <img :src="item" :style="maxHeight" :onerror="$ERRORPIC.noGoods" />
      </van-swipe-item>
    </van-swipe>
    <van-cell>
      <div class="title">{{ goods_detail.goods_name }}</div>
      <div class="price">
        <span>{{goodsPrice | yuan}}</span>
        <span class="stock">库存{{countStock}}件</span>
      </div>
    </van-cell>
    <van-cell :title="sku_selectedText" is-link @click="onSku" />
    <van-sku
      v-model="showSku"
      :sku="goodsSku"
      :show-add-cart-btn="false"
      :goods="goodsInfo"
      :goods-id="goods_detail.goods_id"
      close-on-click-overlay
      :custom-stepper-config="customStepperConfig"
      :quota="quota"
      @buy-clicked="onBuyNow"
      @sku-selected="onSkuSelect"
    >
      <div slot="sku-header-price" slot-scope="props">
        <div class="van-sku__goods-price">
          <span>{{goodsPrice | yuan}}</span>
        </div>
      </div>
      <div slot="sku-actions" slot-scope="props" v-if="goods_state !== null">
        <div class="van-sku-actions">
          <van-button
            type="primary"
            bottom-action
            @click="props.skuEventBus.$emit('sku:buy')"
            v-if="goods_state === 1"
          >立即购买</van-button>
          <van-button
            type
            bottom-action
            @click="props.skuEventBus.$emit('sku:buy')"
            disabled
            v-else
          >{{goods_state_text}}</van-button>
        </div>
      </div>
    </van-sku>
  </van-cell-group>
</template>

<script>
import { Swipe, SwipeItem, Sku } from "vant";
import { isEmpty } from "@/utils/util";
import { _encode } from "@/utils/base64";
import { bindMobile } from "@/mixins";
export default {
  data() {
    return {
      showSku: false,
      sku_selectedNum: 1,
      sku_selectedComb: null,

      goodsSkus: {}
    };
  },
  props: {
    goods_detail: Object,
    orderType: {
      // 确认类型 2 ==> 立即开店 /  3 ==> 立即续费 / 4 ==>立即升级
      type: [String, Number],
      required: true
    }
  },
  mixins: [bindMobile],
  computed: {
    maxHeight() {
      return {
        maxHeight: document.body.offsetWidth + "px"
      };
    },
    // 商品状态 1==> 正常，-1==> 无库存 ，其他均不可操作
    goods_state() {
      let state = null;
      if (this.goods_detail && this.goods_detail.state) {
        this.countStock == 0 ? (state = -1) : (state = this.goods_detail.state);
      } else if (this.goods_detail.state == 0) {
        state = 0;
      }
      return state;
    },
    goods_state_text() {
      return this.goods_state == -1 ? "商品已售罄" : "商品已下架";
    },
    goodsPrice() {
      let price = parseFloat(
        this.sku_selectedComb
          ? this.sku_selectedComb.price / 100
          : this.goodsSku.price
      );
      return price;
    },
    // 转换sku列表数据 ( 元 => 分 )
    tranList() {
      const list = this.goods_detail.sku.list;
      list.forEach(e => {
        e.price = parseFloat(e.price);
      });

      return list;
    },
    // 计算总库存
    countStock() {
      const list = this.goods_detail.sku ? this.goods_detail.sku.list : [];
      let stock = 0;
      if (list && !isEmpty(list)) {
        list.forEach(e => {
          stock += parseInt(e.stock_num);
        });
      }
      return stock;
    },
    goodsInfo() {
      return {
        title: this.goods_detail.goods_name,
        picture: this.goods_detail.goods_images
          ? this.$BASESRC(this.goods_detail.goods_images[0])
          : ""
      };
    },
    goodsSku() {
      const $this = this;
      const goods = $this.goods_detail;

      if (goods.sku) {
        $this.goodsSkus = {
          tree: goods.sku.tree ? goods.sku.tree : [],
          list: $this.tranList,
          price: goods.min_price,
          stock_num: $this.countStock, // 商品总库存
          collection_id: isEmpty(goods.sku.tree) ? $this.tranList[0].id : 0, // 无规格商品 skuId 取 collection_id，否则取所选 sku 组合对应的 id
          none_sku: isEmpty(goods.sku.tree) // 是否无规格商品
        };
      }
      return $this.goodsSkus;
    },
    sku_selectedText() {
      const $this = this;
      let text = "";
      if ($this.goodsSkus.none_sku) {
        text = "已选：" + $this.sku_selectedNum;
      } else {
        if ($this.sku_selectedComb) {
          text = "已选：" + $this.sku_selectedComb.sku_name;
        } else {
          text = "请选择规格";
        }
      }
      return text;
    },
    // sku限购数量
    quota() {
      const $this = this;
      const goodsSku = isEmpty($this.goodsSku) ? null : $this.goodsSku;
      const sku_selectedComb = $this.sku_selectedComb;
      let quota = -1;
      if (goodsSku) {
        if (!goodsSku.none_sku && sku_selectedComb) {
          // console.log("有规格商品并已选规格");
          quota = sku_selectedComb.max_buy;
        } else if (goodsSku.none_sku) {
          // console.log("无规格商品");
          quota = goodsSku.list[0].max_buy;
        }
      }
      return quota;
    },
    customStepperConfig() {
      const $this = this;
      const quotaText = $this.quota == -1 ? "" : "限购" + $this.quota + "件";
      return {
        handleOverLimit: data => {
          const { action, limitType, quota, quotaUsed } = data;
          if (action === "minus") {
            $this.$Toast("至少选择一件！");
          } else if (action === "plus") {
            $this.$Toast(limitType === 1 ? "库存不足！" : `限购${quota}件！`);
          }
        },
        handleStepperChange: num => {
          // 限制最大输入数量
          const limitFlag = $this.quota > 0; // 活动限购量 真为限购 否为不限购
          let stock = 0; // 库存量
          if (!$this.goodsSkus.none_sku && $this.sku_selectedComb) {
            stock = $this.sku_selectedComb.stock_num;
          } else {
            stock = $this.countStock;
          }
          let limitNum = $this.quota > stock ? stock : $this.quota; //限购量不能大于库存
          $this.sku_selectedNum = limitFlag
            ? num > limitNum
              ? limitNum
              : num
            : num > stock
            ? stock
            : num;
        }
      };
    }
  },
  methods: {
    onSku(type) {
      const $this = this;
      $this.showSku = true;
    },
    // 立即购买
    onBuyNow(data) {
      const $this = this;
      $this.bindMobile().then(() => {
        const params = {};
        params.sku_list = [];
        params.order_type = $this.orderType;
        let sku_list_obj = {};
        sku_list_obj.num = data.selectedNum > 0 ? data.selectedNum : 1; //已购买的数量
        sku_list_obj.sku_id = data.selectedSkuComb.id; //sku的Id
        params.sku_list.push(sku_list_obj);
        $this.$router.push({
          name: "microshop-confirmorder",
          query: {
            params: _encode(JSON.stringify(params))
          }
        });
      });
    },
    // 选择规格
    onSkuSelect(data) {
      this.sku_selectedComb = data.selectedSkuComb;
    }
  },
  components: {
    [Swipe.name]: Swipe,
    [SwipeItem.name]: SwipeItem,
    [Sku.name]: Sku
  }
};
</script>

<style scoped>
.swipe img {
  width: 100%;
  height: auto;
  display: block;
}

.title {
  font-size: 16px;
  height: 48px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  flex: auto;
  color: #333;
}

.price {
  color: #ff454e;
  font-size: 16px;
  font-weight: 800;
  height: 26px;
}

.price .stock {
  font-weight: 400;
  color: #999;
  font-size: 12px;
  margin-left: 10px;
}
</style>

